package com.technology.education.ui.student

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.View
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.google.gson.Gson
import com.technology.education.MyApplication
import com.technology.education.data.AppData
import com.technology.education.data.SpKeys
import com.technology.education.data.model.CallEventModel
import com.technology.education.databinding.ActivityMainStudentBinding
import com.technology.education.ext.*
import com.technology.education.network.apiService
import com.technology.education.ui.common.login.ActivityLogin
import com.tencent.liteav.trtccalling.TUICalling
import com.tencent.liteav.trtccalling.TUICallingImpl
import com.tencent.liteav.trtccalling.model.TRTCCalling
import com.tencent.liteav.trtccalling.model.impl.base.CallModel
import com.tencent.liteav.trtccalling.model.impl.base.SignallingData
import me.hgj.jetpackmvvm.base.activity.BaseVmDbActivity
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.lifecycle.KtxActivityManger
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.util.startActivity

class MainStudentActivity : BaseVmDbActivity<BaseViewModel, ActivityMainStudentBinding>() {

    override fun initView(savedInstanceState: Bundle?) {
        initIM()
        getUserInfo()
        getRule()
        startLocation()
        requestPermissions(
            arrayOf(
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION
            ), 22
        )
        initVideoCall()
    }

    private fun initVideoCall() {
        TUICallingImpl.sharedInstance(appContext).enableFloatWindow(true)
        TUICallingImpl.sharedInstance(applicationContext)
            .setCallingListener(object : TUICalling.TUICallingListener {
                override fun clickEvent(type: TUICalling.ClickType?) {

                }

                override fun shouldShowOnCallView(): Boolean {
                    return true
                }

                override fun onCallStart(
                    userIDs: Array<out String>?,
                    type: TUICalling.Type?,
                    role: TUICalling.Role?,
                    tuiCallingView: View?
                ) {

                }

                override fun onCallEnd(
                    userIDs: Array<out String>?,
                    type: TUICalling.Type?,
                    role: TUICalling.Role?,
                    totalTime: Long
                ) {
                }

                override fun onCallEvent(
                    event: TUICalling.Event?,
                    type: TUICalling.Type?,
                    role: TUICalling.Role?,
                    message: String?
                ) {
                }

                override fun onEvent(inviteId: String?, data: String?, type: Int) {
                    data?.let {
                        getAppViewModel().pushMessage(
                            Gson().toJson(
                                CallEventModel(
                                    inviteId ?: "",
                                    AppData.USER_ID,
                                    data,
                                    type
                                )
                            ), SpKeys.VIDEO_HANG_UP, AppData.CURRENT_INVITER
                        )
                    }

                }

                override fun endVideo() {
                    AppData.CURRENT_INVITER = ""
                    AppData.CURRENT_INVITE_ID = ""
                }

                override fun onUserEnter(userId: String?) {
                }

                override fun onError(code: Int, msg: String?) {
                    showLog("onError***$code--$msg")
                    getAppViewModel().pushMessage(
                        Gson().toJson(
                            CallEventModel(
                                AppData.CURRENT_INVITE_ID,
                                AppData.USER_ID,
                                msg ?: "",
                                CallModel.VIDEO_CALL_ACTION_HANGUP
                            )
                        ), SpKeys.VIDEO_HANG_UP, AppData.CURRENT_INVITER
                    )
                }

            })
    }

    private fun getRule() {
        mViewModel.request({ apiService.exchangeRule() }, success = {
            getAppViewModel().exchangeRule = it
        })
    }

    /**
     * 开启定位
     */
    private var location: LocationClient? = null
    private fun startLocation() {
        LocationClient.setAgreePrivacy(true)
        try {
            location = LocationClient(MyApplication.context, LocationClientOption().apply {
                isOnceLocation = true
                setIsNeedAddress(true)
            })
            location?.registerLocationListener(object : BDAbstractLocationListener() {
                override fun onReceiveLocation(result: BDLocation?) {
                    result?.let {
                        if (it.city.isNullOrEmpty()) {
                            return
                        }
                        updateLocation(it)
                        getAppViewModel().city.postValue(it.city ?: "未知")
                    }
                }

            })
        } catch (e: Exception) {

        }
    }

    private fun updateLocation(bdLocation: BDLocation) {
        mViewModel.request(
            {
                apiService.saveLocation(
                    hashMapOf(
                        "address" to bdLocation.addrStr,
                        "city" to bdLocation.city,
                        "district" to bdLocation.district,
                        "province" to bdLocation.province
                    )
                )
            },
            success = {})
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 22) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                location?.start()
            }
        }
    }

    private fun getUserInfo() {
        getAppViewModel().getInfo()
    }

    override fun showLoading(message: String) {
    }

    override fun dismissLoading() {
    }

    override fun createObserver() {
        observe(SpKeys.RELOGIN, String::class.java) {
            if (it == "401") {
                KtxActivityManger.finishAllActivity()
                saveData(SpKeys.IS_LOGIN, false)
                startActivity(ActivityLogin::class)
            }
        }
    }

    var currentTime: Long = 0
    override fun onBackPressed() {
        if (fragmentInStackSize() == 1) {
            ///这里做一个判断当前是否在主页面,如果在则提示退出操作
            if (System.currentTimeMillis() - currentTime >= 2 * 1000) {
                toast("再按一次退出应用")
                currentTime = System.currentTimeMillis()
            } else {
                finish()
            }
        } else {
            super.onBackPressed()
        }
    }
}